﻿using UnityEditor;
using UnityEngine;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using QPEngine;
using LitJson;

namespace QPTools
{
    public class BuildAsset
    {
        public static string platform = string.Empty;
        static List<string> paths = new List<string>();
        static List<string> files = new List<string>();
        static List<string> EncryptionFilesName = new List<string>();

        /// <summary>
        /// 初始化配置
        /// </summary>
        public static void InitConfiger()
        {
            string ConfigerName = AppConst.CSConfigerName;
            string path = PathHelp.AppResPath + ConfigerName;
            string txt = File.ReadAllText(path);
            //UnityEngine.Debug.Log(txt);
            if (!txt.Contains(AppConst.ConstCode)) { txt = MD5Helper.DecryptDES(txt); }
            AppConst.csConfiger = JsonMapper.ToObject<CSConfiger>(txt);

        }



        [MenuItem("Tools/Creater iOS AB", false, 11)]
        public static void BuildiOSResource()
        {
            BuildTarget target = BuildTarget.iOS;
            Log.Debug($"开始编译{target.ToString()}平台的AB资源");
            InitConfiger();
            BuildAssetResource(target);
        }



        [MenuItem("Tools/Creater Android AB", false, 12)]
        public static void BuildAndroidResource()
        {
            BuildTarget target = BuildTarget.Android;
            Log.Debug($"开始编译{target.ToString()}平台的AB资源");
            InitConfiger();
            BuildAssetResource(target);
        }



        [MenuItem("Tools/Creater WIN AB", false, 13)]
        public static void BuildWINResource()
        {
            BuildTarget target = BuildTarget.StandaloneWindows;
            Log.Debug($"开始编译{target.ToString()}平台的AB资源");
            InitConfiger();
            BuildAssetResource(target);
        }
        /// <summary>
        /// 编译AssetResource
        /// </summary>
        public static void BuildAssetResource(BuildTarget target)
        {
            Caching.ClearCache();
            string resPath = PathHelp.AppResPath;
            if (Directory.Exists(PathHelp.AppHotfixResPath)) { Directory.Delete(PathHelp.AppHotfixResPath, true); }

            BuildPipeline.BuildAssetBundles(resPath, BuildAssetBundleOptions.ChunkBasedCompression, target);
            paths.Clear();
            files.Clear();
            Recursive(resPath);
            OnHandleConfiger();
            AssetDatabase.Refresh();
            Log.Debug("AB资源编译完成");
        }

        /// <summary>
        /// 数据目录
        /// </summary>
        static string AppDataPath
        {
            get { return Application.dataPath; }
        }

        /// <summary>
        /// 遍历目录及其子目录
        /// </summary>
        static void Recursive(string path)
        {
            string[] names = Directory.GetFiles(path);
            string[] dirs = Directory.GetDirectories(path);
            foreach (string filename in names)
            {
                string ext = Path.GetExtension(filename);
                if (ext.Equals(".meta")) continue;
                files.Add(filename.Replace('\\', '/'));
            }
            foreach (string dir in dirs)
            {
                paths.Add(dir.Replace('\\', '/'));
                Recursive(dir);
            }
        }

        //public static void UpdateProgress(int progress, int progressMax, string desc)
        //{
        //    string title = "Processing...[" + progress + " - " + progressMax + "]";
        //    float value = (float)progress / (float)progressMax;
        //    EditorUtility.DisplayProgressBar(title, desc, value);
        //}



        /// <summary>
        /// 处理配置文件
        /// </summary>
        public static void OnHandleConfiger()
        {
            //处理 ValueConfiger 配置
            string resPath = AppDataPath + "/" + AppConst.StreamingAssetsName;
            string ValueConfigerPath = resPath + "/" + AppConst.ValueConfigerName;
            Dictionary<string, BaseValueConfigerJson> bvj = new Dictionary<string, BaseValueConfigerJson>();
            for (int i = 0; i < files.Count; i++)
            {
                string file = files[i];
                if (file.EndsWith(".meta") || file.Contains(".DS_Store")) continue;
                BaseValueConfigerJson ValueConfigerJson = new BaseValueConfigerJson();
                ValueConfigerJson.md5 = MD5Helper.MD5File(file);
                ValueConfigerJson.dirPath = file.Replace(resPath, string.Empty).TrimStart('/');
                ValueConfigerJson.name = Path.GetFileName(file);
                if (file.EndsWith(".unity3d"))
                {
                    uint crc = 0;
                    Hash128 hash;
                    BuildPipeline.GetCRCForAssetBundle(file, out crc);
                    BuildPipeline.GetHashForAssetBundle(file, out hash);
                    ValueConfigerJson.crc = crc;
                    ValueConfigerJson.hash = hash.ToString();
                }
                bvj.Add(ValueConfigerJson.name, ValueConfigerJson);
            }
            ValueConfiger valueConfiger = new ValueConfiger();
            valueConfiger.AuthCode = AppConst.AuthCode;
            valueConfiger.Version = 1;
            valueConfiger.JsonData = bvj;
            string valueConfigerTxt = JsonMapper.ToJson(valueConfiger);
            File.Delete(ValueConfigerPath);
            File.AppendAllText(ValueConfigerPath, valueConfigerTxt);


            //处理 UpdateConfiger 配置
            string UpdateConfigerPath = resPath + "/" + AppConst.UpdateConfigerName;
            List<BaseValueConfigerJson> bfj = new List<BaseValueConfigerJson>();
            for (int i = 0; i < files.Count; i++)
            {
                string file = files[i];
                if (file.EndsWith(".meta") || file.Contains(".DS_Store")) continue;

                BaseValueConfigerJson UpdateConfigerJosn = new BaseValueConfigerJson();
                UpdateConfigerJosn.md5 = MD5Helper.MD5File(file);
                UpdateConfigerJosn.dirPath = file.Replace(resPath, string.Empty).TrimStart('/');
                if (file.EndsWith(".unity3d"))
                {
                    uint crc = 0;
                    Hash128 hash;
                    BuildPipeline.GetCRCForAssetBundle(file, out crc);
                    BuildPipeline.GetHashForAssetBundle(file, out hash);
                    UpdateConfigerJosn.crc = crc;
                    UpdateConfigerJosn.hash = hash.ToString();
                }
                bfj.Add(UpdateConfigerJosn);
            }

            string CSConfigerName = AppConst.CSConfigerName;
            string CSConfigerNameOldPath = Application.dataPath + "/Resources/" + CSConfigerName;
            string CSConfigerNameNewPath = Application.dataPath + "/StreamingAssets/";

            if (File.Exists(CSConfigerNameOldPath))
            {
                if (AppConst.FileNameEncryption) { CSConfigerName = MD5Helper.MD5File(AppConst.CSConfigerName.Split('.')[0]) + ".txt"; }
                //File.Copy(path, newpath, true);
                string str = File.ReadAllText(CSConfigerNameOldPath);
                str = MD5Helper.EncryptDES(str);
                CSConfigerNameNewPath += CSConfigerName;
                File.Delete(CSConfigerNameNewPath);
                File.AppendAllText(CSConfigerNameNewPath, str);
            }

            //获取之前配置的部分信息
            string oldTxt = string.Empty;
            UpdateConfiger uc;
            int version = 0;
            try
            {
                oldTxt = File.ReadAllText(UpdateConfigerPath);
                uc = JsonMapper.ToObject<UpdateConfiger>(oldTxt);
                version = uc.Version;
            }
            catch (System.Exception)
            {
            }

            //保存到json配置
            BaseValueConfigerJson CSConfigerJson = new BaseValueConfigerJson();
            CSConfigerJson.md5 = MD5Helper.MD5File(CSConfigerNameOldPath);
            CSConfigerJson.dirPath = CSConfigerName;

            BaseValueConfigerJson ValueConfigerJsonFile = new BaseValueConfigerJson();
            ValueConfigerJsonFile.md5 = MD5Helper.MD5File(ValueConfigerPath);
            ValueConfigerJsonFile.dirPath = AppConst.ValueConfigerName;

            bfj.Add(CSConfigerJson);
            bfj.Add(ValueConfigerJsonFile);
            UpdateConfiger updateConfiger = new UpdateConfiger();
            updateConfiger.JsonData = bfj.ToArray();
            updateConfiger.AuthCode = AppConst.AuthCode;
            updateConfiger.Version = version;
            string newTxt = JsonMapper.ToJson(updateConfiger);
            File.Delete(UpdateConfigerPath);
            File.AppendAllText(UpdateConfigerPath, newTxt);

        }


    }
}